﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using OpalisConsole.EndUserService;

namespace OpalisConsole.Views.Administration.Child_Windows
{
    public partial class AuthorizationDetailsWindow : ChildWindow
    {
        private ObservableCollection<WorkLogEntry> workLog;
        public String Status = String.Empty;
        public AuthorizationRequest req;
        public String rejectionMessage = String.Empty;
        public AuthorizationDetailsWindow(AuthorizationRequest request)
        {
            InitializeComponent();

            boxMachine.Text = request.MachineName;
            boxRequester.Text = request.DisplayName;
            boxStatus.Text = request.Status;

            req = request;

            if (request.MachineName.Equals("Not Found"))
            {
                ApproveButton.IsEnabled = false;
            }
            else
            {
                EndUserServiceSoapClient EndUserProxy = new EndUserServiceSoapClient();
                EndUserProxy.getMachineDataCompleted += new EventHandler<getMachineDataCompletedEventArgs>(EndUserProxy_getMachineDataCompleted);
                EndUserProxy.getMachineDataAsync(request.MachineName);
            }

            busyIndicatorMain.IsBusy = true;
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.getSoftwareDataCompleted += new EventHandler<getSoftwareDataCompletedEventArgs>(proxy_getSoftwareDataCompleted);
            proxy.getSoftwareDataAsync(request.UserName.ToString(), App.Current.Resources["UserDomain"].ToString());
        }

        void EndUserProxy_getMachineDataCompleted(object sender, getMachineDataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                throw new Exception();
            }
            else
            {
                MachineData md = (MachineData)e.Result;
                if (!(md.ProcessorNumber==null))
                {
                    boxNumProcessors.Text = md.ProcessorNumber;
                }
                if (!(md.MachineType == null))
                {
                    boxMachineType.Text = md.MachineType;
                }
                if (!(md.RAMAmount == null))
                {
                   boxRAM.Text = md.RAMAmount;
                }
                if (!(md.TopConsoleUser == null))
                {
                    boxSCCMOwner.Text = md.TopConsoleUser;
                }
            }
        }
        void proxy_getSoftwareDataCompleted(object sender, getSoftwareDataCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                throw new Exception();
            }
            else
            {
                System.Collections.ObjectModel.ObservableCollection<SoftwareData> SortedList = new System.Collections.ObjectModel.ObservableCollection<SoftwareData>();

                Dictionary<String, SoftwareData> keyListAuto = new Dictionary<String, SoftwareData>();
                Dictionary<String, SoftwareData> keyListSelf = new Dictionary<String, SoftwareData>();
                Dictionary<String, SoftwareData> keyListCannot = new Dictionary<String, SoftwareData>();

                foreach (SoftwareData data in e.Result)
                {
                    if (data.Status.Equals("Cannot be Reinstalled"))
                    {
                        keyListCannot.Add(data.PackageName, data);
                    }
                    if (data.Status.Equals("Automatically Installed"))
                    {
                        keyListAuto.Add(data.PackageName, data);
                    }
                    if (data.Status.Equals("Self Install"))
                    {
                        keyListSelf.Add(data.PackageName, data);
                    }
                }

                var itemsAuto = from k in keyListAuto.Keys
                                orderby keyListAuto[k] ascending
                                select k;
                var itemsManual = from k in keyListSelf.Keys
                                  orderby keyListSelf[k] ascending
                                  select k;
                var itemsCannot = from k in keyListCannot.Keys
                                  orderby keyListCannot[k] ascending
                                  select k;

                foreach (String key in keyListCannot.Keys)
                {
                    SortedList.Add(keyListCannot[key]);
                }
                foreach (String key in keyListSelf.Keys)
                {
                    SortedList.Add(keyListSelf[key]);
                }
                foreach (String key in keyListAuto.Keys)
                {
                    SortedList.Add(keyListAuto[key]);
                }

                gridSoftwareValidation.ItemsSource = SortedList;
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getRequestWorkLogCompleted +=new EventHandler<getRequestWorkLogCompletedEventArgs>(proxy_getRequestWorkLogCompleted_INIT);
                proxy.getRequestWorkLogAsync(req);
            }
        }
        void proxy_getRequestWorkLogCompleted_INIT(object sender, getRequestWorkLogCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            workLog = new ObservableCollection<WorkLogEntry>();
            if (e.Result.Count > 0)
            {
                foreach (WorkLogEntry entry in e.Result)
                {
                    WorkLogEntry modifiedEntry = entry;
                    modifiedEntry.NoteDate = modifiedEntry.NoteDate.ToLocalTime();

                    workLog.Add(modifiedEntry);
                }
            }
            gridWorkLog.ItemsSource = workLog;
        }
        private void gridSoftwareValidation_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            DataGridRow row = e.Row;
            SoftwareData data = (SoftwareData)row.DataContext;

            switch (data.Status)
            {
                case "Automatically Installed":
                    e.Row.Foreground = new SolidColorBrush(Colors.Black);
                    break;
                case "Self Install":
                    e.Row.Foreground = new SolidColorBrush(Colors.Blue);
                    break;
                case "Cannot be Reinstalled":
                    e.Row.Foreground = new SolidColorBrush(Colors.Red);
                    break;
            }
        }
        private void ApproveButton_Click(object sender, RoutedEventArgs e)
        {
            Status = "Approved";
            req.Status = "Approved";
            this.DialogResult = true;
        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
        private void RejectButton_Click(object sender, RoutedEventArgs e)
        {
            Status = "Rejected";

            RejectionMessage rejectWindow = new RejectionMessage();
            rejectWindow.Closed += new EventHandler(rejectWindow_Closed);
            rejectWindow.Show();
        }
        void rejectWindow_Closed(object sender, EventArgs e)
        {
            rejectionMessage = ((RejectionMessage)sender).boxRejectionMessage.Text;
            if (((RejectionMessage)sender).DialogResult == true)
            {
                if (((RejectionMessage)sender).boxRejectionMessage.Text != null && ((RejectionMessage)sender).boxRejectionMessage.Text != String.Empty)
                {
                    busyIndicatorMain.IsBusy = true;
                    busyIndicatorMain.BusyContent = "Rejecting Request";
                    EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                    proxy.RemoveComputerFromApproveComptuersAsync(boxMachine.Text);
                    proxy.RemoveComputerFromApproveComptuersCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_RemoveComputerFromApproveComptuersCompleted);
                }
            }
            this.DialogResult = true;
        }

        void proxy_RemoveComputerFromApproveComptuersCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.AddRejectionMessageCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_AddRejectionMessageCompleted);
            proxy.AddRejectionMessageAsync(boxMachine.Text, boxRequester.Text, rejectionMessage);
        }

        void proxy_AddRejectionMessageCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            String requester = App.Current.Resources["UserID"].ToString();
            String reqDomain = App.Current.Resources["UserDomain"].ToString();
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.closePendingApprovalRequestCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_closePendingApprovalRequestCompleted);
            proxy.closePendingApprovalRequestAsync(req.MachineName, req.UserName, "Rejected", requester, reqDomain);
            req.Status = "Rejected";
        }

        void proxy_closePendingApprovalRequestCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            this.DialogResult = true;
        }
        private void PendingButton_Click(object sender, RoutedEventArgs e)
        {
            req.Status = "Pending";
            this.DialogResult = true;
        }
        private void btnAddWorklogEntry_Click(object sender, RoutedEventArgs e)
        {
            string username = App.Current.Resources["UserID"].ToString();
            string domain = App.Current.Resources["UserDomain"].ToString();
            
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            
            proxy.getUserFriendlyNameCompleted += new EventHandler<getUserFriendlyNameCompletedEventArgs>(proxy_getUserFriendlyNameCompleted_AddWorkLogEntry);
            proxy.getUserFriendlyNameAsync(username, domain);
            busyIndicatorMain.BusyContent = "Creating New Work Log Entry";
            busyIndicatorMain.IsBusy = true;
        }
        void proxy_getUserFriendlyNameCompleted_AddWorkLogEntry(object sender, getUserFriendlyNameCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            WorkLogEntry entry = new WorkLogEntry()
            {
                Note = String.Empty,
                NoteDate = DateTime.UtcNow,
                RequestID = req.ApprovalID,
                UserName = e.Result.ToString(),
                WorkLogID = System.Guid.NewGuid().ToString()
            };

            WorkLogEntryDetails childWindow = new WorkLogEntryDetails(entry);
            childWindow.Closed += new EventHandler(childWindow_Closed_WorkLogEntry);

            childWindow.Show();
        }
        private void gridWorkLog_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            WorkLogEntry entry = (WorkLogEntry)gridWorkLog.SelectedItem;
            if (entry != null)
            {
                WorkLogEntryDetails childWindow = new WorkLogEntryDetails(entry);
                childWindow.boxWorkLogNotes.IsReadOnly = true;
                childWindow.Show();
            }
        }
        void childWindow_Closed_WorkLogEntry(object sender, EventArgs e)
        {
            WorkLogEntryDetails childWindow = (WorkLogEntryDetails)sender;
            if (childWindow.DialogResult.Value == true)
            {
                busyIndicatorMain.IsBusy = true;
                busyIndicatorMain.BusyContent = "Saving Work Log Entry";
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.createWorkLogEntryCompleted += new EventHandler<createWorkLogEntryCompletedEventArgs>(proxy_createWorkLogEntryCompleted);
                proxy.createWorkLogEntryAsync(childWindow.entry.UserName, childWindow.entry.RequestID, childWindow.entry.Note, childWindow.entry.NoteDate);
            }
        }

        void proxy_createWorkLogEntryCompleted(object sender, createWorkLogEntryCompletedEventArgs e)
        {
            busyIndicatorMain.IsBusy = false;
            WorkLogEntry modifiedWorkLogEntry = e.Result;
            modifiedWorkLogEntry.NoteDate = modifiedWorkLogEntry.NoteDate.ToLocalTime();
            workLog.Add(modifiedWorkLogEntry);
        }
    }
}

